var express = require('express');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var zookeeper = require('node-zookeeper-client');
var fs = require("fs");

var app = express();
var client = zookeeper.createClient('localhost:2181');
var database = path.join(__dirname, 'database');

app.engine('html', require('ejs').renderFile);
// 定义EJS模板引擎和模板文件位置，也可以使用jade或其他模型引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// app.set('views', __dirname );
// 定义icon图标
app.use(favicon(__dirname + '/public/favicon.ico'));
// 定义日志和输出级别
app.use(logger('dev'));
// 定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 定义cookie解析器
app.use(cookieParser());
// 定义静态文件目录
app.use(express.static(path.join(__dirname, 'public')));



// 404错误处理
// app.use(function(req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });
// 开发环境，500错误处理和错误堆栈跟踪
// if (app.get('env') === 'development') {
//   app.use(function(err, req, res, next) {
//     res.status(err.status || 500);
//     res.render('error', {
//       message: err.message,
//       error: err
//     });
//   });
// }
// 生产环境，500错误处理
// app.use(function(err, req, res, next) {
//   res.status(err.status || 500);
//   res.render('error', {
//     message: err.message,
//     error: {}
//   });
// });




client.on('state', function (state) {
    if (state === zookeeper.State.SYNC_CONNECTED) {
        console.log('Client state is changed to connected.');
    }
});
function listChildren(client, path) {
    client.getChildren(
        path,
        function (event) {
            console.log('Got watcher event: %s', event);
            listChildren(client, path);
        },
        function (error, children, stat) {
            if (error) {
                console.log(
                    'Failed to list children of %s due to: %s.',
                    path,
                    error
                );
                return;
            }

            console.log('Children of %s are: %j.', path, children);
        }
    );
}

client.once('connected', function () {
    console.log('Connected to ZooKeeper.');
    listChildren(client, "/");
});

client.connect();



app.get('/', function(req, res){
  // res.send('hello world');
  res.render("index");
});


app.get("/table_advanced.html",function(req,res){
	res.render("table_advanced");
});
app.get("/table_basic.html",function(req,res){
	res.render("table_basic");
});
app.get("/table_editable.html",function(req,res){
	res.render("table_editable");
});
app.get("/table_managed.html",function(req,res){
	res.render("table_managed");
});
app.get("/table_responsive.html",function(req,res){
	res.render("table_responsive");
});

app.get("/zkhost.html",function(req,res){
	res.render("zk_host");
});

fs.exists(database, function (exists) {
  console.log(exists ? "database exists" : "database not exists!");
  if(!exists){
  	fs.mkdir(database,0777,function(err){
  		console.error(err);
  	});
  }else{
  	var config = JSON.stringify([{name:"a",host:"127.0.0.1",port:2181},{name:"b",host:"127.0.0.1",port:2182}]);
  	fs.writeFile(database + '/config.json', config, function (err) {
	  if (err) throw err;
	  console.log('It\'s saved!'); //文件被保存
	  console.log("config : %j ", JSON.parse(fs.readFileSync(database + '/config.json')));
	});	
  }
});
fs.watchFile(database + '/config.json', function (curr, prev) {
  console.log('the current mtime is: ' + curr.mtime);
  console.log('the previous mtime was: ' + prev.mtime);
});
fs.watch(database + '/config.json', function (event, filename) {
  console.log('event is: ' + event);
  if (filename) {
    console.log('filename provided: ' + filename);
  } else {
    console.log('filename not provided');
  }
});
app.post("/zookeeper-directory",function(req,res){
    var data = [];
     data[0]={"name":"shihui","id":"/shihui","path":"/shihui","isParent":"true"};
     data[1]={"name":"shihui/name","id":"/name","path":"/shihui/name","isParent":"false"};     
     res.json(data);
});
app.listen(3000);